#include "chatwindow.h"


ChatWindow::ChatWindow(QWidget *parent)
    : QMainWindow(parent)

{
}


ChatWindow::ChatWindow(const ChatConfig &config, QWidget *parent)
    : QMainWindow(parent), m_config(config)
    , chatSession(nullptr)
    , isGenerating(false)
    , m_speechManager(new SpeechManager(this))
    , m_visionManager(new VisionManager(this))
{
    initUI();
    initChat();
}



ChatWindow::~ChatWindow()
{
    if (chatSession) {
        genai_text_destroy_session(&chatSession);
    }
    if (historyMessages) {
        chat_message_destroy(&historyMessages);
    }
}

void ChatWindow::initUI()
{
    // 创建中心部件
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    // 创建布局
    layout = new QHBoxLayout(centralWidget);

    historyLayout=new QVBoxLayout();
    historyLayout->setAlignment(Qt::AlignTop);
    mainLayout=new QVBoxLayout();

    chatLayout= new QHBoxLayout();

    chatHistory = new QTextEdit(this);
    chatHistory->setReadOnly(true);

    chatHistoryCursor = new QTextCursor(chatHistory->document());

    chatLayout->addWidget(chatHistory);

    layout->addLayout(historyLayout);
    layout->addLayout(mainLayout);

    mainLayout->addLayout(chatLayout);
    // 创建按钮布局
    buttonLayout = new QHBoxLayout();
    saveButton = new QPushButton("保存聊天记录", this);
    visionButton = new QPushButton("上传图片", this);
    buttonLayout->addWidget(saveButton);
    buttonLayout->addWidget(visionButton);

    mainLayout->addLayout(buttonLayout);


    historyDirWatcher=new QFileSystemWatcher(this);
    historyDirWatcher->addPath(historyDirPath);
    connect(historyDirWatcher, &QFileSystemWatcher::directoryChanged, this, &ChatWindow::updateHistoryDir);
    updateHistoryDir();

    // 创建输入区域
    inputLayout = new QHBoxLayout();
    inputField = new ChatTextEdit(this);
    inputField->setMaximumHeight(200);
    sendButton = new QPushButton("发送", this);
    inputLayout->addWidget(inputField);
    inputLayout->addWidget(sendButton);
    mainLayout->addLayout(inputLayout);

    connect(sendButton, &QPushButton::clicked, this, &ChatWindow::sendMessage);
    connect(inputField, &ChatTextEdit::enterPressed, this, &ChatWindow::sendMessage);
    connect(saveButton, &QPushButton::clicked, this, &ChatWindow::saveChatHistory);
    // 初始化语音管理器
    if (!m_speechManager->initialize()) {
        QMessageBox::critical(this, "错误", "语音识别初始化失败");
    }
    // 设置麦克风按钮
    micButton = new QPushButton("语音输入", this);
    buttonLayout->addWidget(micButton);
    connect(micButton, &QPushButton::clicked,
            this, &ChatWindow::onMicButtonClicked);
    connect(m_speechManager,&SpeechManager::recognitionResult,this,&ChatWindow::onRecognitionData);

    if(!m_visionManager->initialize()){
        QMessageBox::critical(this, "错误", "图片识别初始化失败");
    }
    connect(visionButton, &QPushButton::clicked, this, &ChatWindow::onVisionButtonClicked);
    connect(m_visionManager, &VisionManager::recognitionFinished,
            this, &ChatWindow::onRecognitionFinished);
    connect(m_visionManager, &VisionManager::recognitionError,
            this, &ChatWindow::onRecognitionError);

    // 设置窗口属性
    resize(1360, 765);
    setWindowTitle("Kylin AI Chat");
    textEditRender();
}

void ChatWindow::initChat()
{
    // 创建会话
    chatSession = genai_text_create_session();
    if (!chatSession) {
        QMessageBox::critical(this, "错误", "创建会话失败");
        return;
    }
    // 初始化会话
    if (genai_text_init_session(chatSession) != 0) {
        QMessageBox::critical(this, "错误", "初始化会话失败");
        genai_text_destroy_session(&chatSession);
        return;
    }

    // 创建历史消息对象
    historyMessages = chat_message_create();
    if (!historyMessages) {
        QMessageBox::critical(this, "错误", "创建历史消息对象失败");
        genai_text_destroy_session(&chatSession);
        return;
    }

    // 设置回调函数
    genai_text_result_set_callback(chatSession, chatCallback, this);

    // 配置模型
    ChatModelConfig *config = chat_model_config_create();
    if (config) {
//        chat_model_config_set_name(config, "default"); // 使用默认模型
//        chat_model_config_set_name(config, "讯飞-Spark Max"); // 使用讯飞-Spark Max
        if(m_config.modelType==0)
        {
            chat_model_config_set_deploy_type(config, ModelDeployType::OnDevice);
        }
        else if(m_config.modelType==1)
        {
            chat_model_config_set_deploy_type(config, ModelDeployType::PublicCloud);
        }
        chat_model_config_set_name(config,m_config.modelName.toUtf8().constData());
        genai_text_set_model_config(chatSession, config);
        chat_model_config_destroy(&config);
    }
    if(m_config.prompt!=""){
        genai_text_clear_chat_history_messages(chatSession);
        genai_text_set_chat_system_prompt(chatSession, m_config.prompt.toUtf8().constData());
        chat_message_add_system_message(historyMessages, m_config.prompt.toUtf8().constData());
    }
    if(m_config.autoSpeech){
        initSpeechSyn();
    }
}
void ChatWindow::initSpeechSyn()
{
    //初始化语音生成器
    m_speechSynthesizer=new SpeechSynthesizer(this);
    if(!m_speechSynthesizer->initialize()){
        QMessageBox::critical(this, "错误", "语音生成初始化失败");
    }
}

void ChatWindow::sendMessage()
{
    QString message = inputField->toPlainText();
    if (message.isEmpty() || !chatSession || !historyMessages)
        return;

    // 检查是否有图片识别结果
    if (!m_visionManager->lastRecognitionResult.isEmpty()) {
        message += "\n[图片内容]: " + m_visionManager->lastRecognitionResult;
        m_visionManager->lastRecognitionResult.clear();
    }

    chat_message_add_user_message(historyMessages, message.toUtf8().constData());
    // 显示用户输入

    //chatHistoryCursor->insertText("User: \t\n",*userContentFormat);
    chatHistory->append("User: \t\n");
    chatHistory->append(message);
    inputField->clear();

    // 清空之前的回答缓存
    currentResponse.clear();
    isGenerating = true;

    // 显示正在思考的提示
    chatHistory->append("\nAssistant: \t\n");
    chatHistory->append("正在思考...");
    lastResponseLine = chatHistory->document()->lineCount() - 1;

    // 禁用输入，直到回答完成
    inputField->setEnabled(false);
    sendButton->setEnabled(false);

    // 使用带历史消息的接口发送对话
    genai_text_chat_with_history_messages_async(chatSession, historyMessages);

    chatHistory->verticalScrollBar()->setValue(chatHistory->verticalScrollBar()->maximum());
}

void ChatWindow::chatCallback(ChatResult *chat_result, void *user_data)
{
    ChatWindow *window = static_cast<ChatWindow*>(user_data);
    if (!window)
        return;

    // 获取助手回复
    const char *response = chat_result_get_assistant_message(chat_result);
    if (response) {
        QString newResponse = QString::fromUtf8(response);

        // 实时更新UI显示
        QMetaObject::invokeMethod(window, "updateResponse",
            Qt::QueuedConnection,
            Q_ARG(QString, newResponse));
    }

    // 检查是否生成结束
    bool is_end = chat_result_get_is_end(chat_result);
    if (is_end) {
        // 在UI线程中更新界面并重置状态
        QMetaObject::invokeMethod(window, "handleCompleteResponse",
            Qt::QueuedConnection);
    }
}

void ChatWindow::updateResponse(const QString &response)
{
    if (m_isFirstResponseSegment) {
        m_fullAssistantResponse.clear();
        m_isFirstResponseSegment = false;}

    // 如果是第一次响应，删除"正在思考..."的临时提示
    if (currentResponse.isEmpty()) {
        QTextDocument *doc = chatHistory->document();
        QTextCursor cursor(doc);
        cursor.movePosition(QTextCursor::End);
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
        cursor.removeSelectedText();
        if (cursor.position() > 0) {
            cursor.deletePreviousChar(); // 删除换行符
        }
    }

    m_fullAssistantResponse += response;

    // 处理响应文本
    QStringList lines = response.split('\n',QString::KeepEmptyParts);

    if (currentResponse.isEmpty()) {
        chatHistory->append(lines.first());
        currentResponse = lines.first();
    } else {
        // 追加到当前行
        currentResponse.append(lines.first());
        QTextCursor cursor = chatHistory->textCursor();
        cursor.movePosition(QTextCursor::End);
        cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
        cursor.removeSelectedText();
        cursor.insertText(currentResponse);
    }

    // 处理剩余的行（如果有）
    for (int i = 1; i < lines.size(); ++i) {
        chatHistory->append(lines[i]);
        currentResponse = lines[i];
    }

}

void ChatWindow::handleCompleteResponse()
{
    try {
        // 添加助手回复到历史
        if (historyMessages && !currentResponse.isEmpty()) {
            QByteArray responseData = currentResponse.toUtf8();
            chat_message_add_assistant_message(historyMessages,
                                               responseData.constData());
        }
        // 重新启用输入
        inputField->setEnabled(true);
        sendButton->setEnabled(true);
        inputField->setFocus();
//        qDebug()<<"currentResponse"+currentResponse;
//        if(m_config.autoSpeech){
//            m_speechSynthesizer->SynthesisOutput(currentResponse.toUtf8());
//        }
        if (m_config.autoSpeech && !m_fullAssistantResponse.isEmpty()) {
            m_speechSynthesizer->SynthesisOutput(m_fullAssistantResponse.toUtf8());
        }
        // 重置状态
        m_fullAssistantResponse.clear();
        m_isFirstResponseSegment = true;
        currentResponse.clear();
        isGenerating = false;

        chatHistory->append("");

    } catch (const std::exception& e) {
        qWarning() << "Exception in handleCompleteResponse:" << e.what();
        chatHistory->append(QString("Error: %1").arg(e.what()));

        // 确保界面恢复可用状态
        inputField->setEnabled(true);
        sendButton->setEnabled(true);
        inputField->setFocus();
    }
}

void ChatWindow::saveChatHistory()
{
    QString fileName = historyDirPath+"/"+QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+".chat";

//    if (fileName.isEmpty())
//        return;

    QFile file(fileName);
    QDir dir(historyDirPath);

    if(!dir.exists())
    {
        dir.mkpath(".");
    }
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", "无法打开文件进行保存");
        return;
    }

    QTextStream out(&file);
    QString content = chatHistory->toPlainText();
    out << content;
    file.close();

    qDebug() << "save as path:" << fileName;
}

void ChatWindow::loadChatHistory(QString fileName)
{
    fileName=historyDirPath+"/"+fileName;

    if (fileName.isEmpty())
        return;

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", "无法打开文件");
        return;
    }

    // 清空当前的历史记录
    if (historyMessages) {
        chat_message_destroy(&historyMessages);
        historyMessages = chat_message_create();
    }

    QTextStream in(&file);
    QString line;
    QString currentRole;
    QString currentMessage;

    while (!in.atEnd()) {
        line = in.readLine();

        if (line.startsWith("User: ")) {
            // 如果之前有未处理的消息，先处理它
            if (!currentMessage.isEmpty() && currentRole == "Assistant") {
                chat_message_add_assistant_message(historyMessages, currentMessage.toUtf8().constData());
            }

            currentRole = "User";
            currentMessage = line.mid(6); // 去掉 "User: " 前缀
        }
        else if (line.startsWith("Assistant: ")) {
            // 如果之前有未处理的消息，先处理它
            if (!currentMessage.isEmpty() && currentRole == "User") {
                chat_message_add_user_message(historyMessages, currentMessage.toUtf8().constData());
            }

            currentRole = "Assistant";
            currentMessage = line.mid(11); // 去掉 "Assistant: " 前缀
        }
        else if (!line.isEmpty()) {
            // 如果不是空行，将其添加到当前消息中
            currentMessage += "\n" + line;
        }
    }

    // 处理最后一条消息
    if (!currentMessage.isEmpty()) {
        if (currentRole == "User") {
            chat_message_add_user_message(historyMessages, currentMessage.toUtf8().constData());
        } else if (currentRole == "Assistant") {
            chat_message_add_assistant_message(historyMessages, currentMessage.toUtf8().constData());
        }
    }

    in.seek(0);

    // 更新界面显示
    chatHistory->clear();
    chatHistory->setPlainText(in.readAll());

    file.close();
}

void ChatWindow::onMicButtonClicked()
{
    if (!m_speechManager->isListening) {
        // 开始前重置状态
        m_speechManager->recognitionData.text.clear();
        m_speechManager->recognitionData.isFinal = false;
        // 开始语音识别
        m_speechManager->startListening();
        micButton->setText("停止");
    } else {
        // 停止语音识别
        m_speechManager->stopListening();
        micButton->setText("语音输入");
        inputField->setEnabled(true);
    }
}

void ChatWindow::onRecognitionData(){
    inputField->setText(m_speechManager->recognitionData.text);
    inputField->setEnabled(false);
    if(m_speechManager->recognitionData.error){
        inputField->setEnabled(true);
        micButton->setEnabled(false);
        micButton->setText("语音识别失败");
    }
    if(m_speechManager->recognitionData.isFinal){
        m_speechManager->isListening=false;
        m_speechManager->stopListening();
        inputField->setEnabled(true);
        micButton->setEnabled(true);
        micButton->setText("语音输入");
    }
}

void ChatWindow::updateHistoryDir()
{
    QLayoutItem *item;

    while(item=(historyLayout->takeAt(0)))
    {
        delete item->widget();
        delete item;
    }

    QDir dir(historyDirPath);
    QStringList files=dir.entryList(QDir::Files);

    for(QString fileName:files)
    {
        QPushButton *button = new QPushButton(fileName, this);
        historyLayout->addWidget(button);
        connect(button,&QPushButton::clicked,[button,this]()
        {
            this->loadChatHistory(button->text());
        });

    }

}

void ChatWindow::textEditRender()
{
    QTextCursor cursor(chatHistory->document());

}


void ChatWindow::onVisionButtonClicked()
{
    QString imagePath = QFileDialog::getOpenFileName(
        this,
        "选择图片",
        QStandardPaths::writableLocation(QStandardPaths::PicturesLocation),
        "Images (*.png *.jpg *.jpeg)"
    );

    if (!imagePath.isEmpty()) {
        // 显示用户上传的图片信息
        chatHistory->append("User: [图片] " + imagePath + "\n");
        chatHistory->append("正在识别图片内容...\n");

        // 调用VisionManager进行识别
        m_visionManager->recognizeImage(imagePath);
    }
}

void ChatWindow::onRecognitionFinished(const QString &text)
{
    // 更新聊天记录
    QTextCursor cursor = chatHistory->textCursor();
    cursor.movePosition(QTextCursor::End);

    // 删除"正在识别..."的提示
    cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
    cursor.removeSelectedText();

    // 添加识别结果
    chatHistory->append("识别完毕");

}

void ChatWindow::onRecognitionError(const QString &error)
{
    // 显示错误信息
    QTextCursor cursor = chatHistory->textCursor();
    cursor.movePosition(QTextCursor::End);

    // 删除"正在识别..."的提示
    cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
    cursor.removeSelectedText();

    chatHistory->append("识别错误: " + error + "\n");
}
